import { percentage, setLocalList } from "../utils";
export default class Evt {
  luckyNum = 0;
  list = [];
  constructor(list) {
    this.list = list;
  }
  write() {
    let n = percentage(this.list.map((n) => n.p));
    this.list.forEach((item, index) => {
      item.lucky = n[index];
    });
    setLocalList(this.list);
  };

  lucky() {
    const list = this.list;
    const randomNum = Math.random() * 100;
    let cureent = 0;
    while (this.luckyNum < list.length) {
      cureent += list[this.luckyNum].lucky;
      if (randomNum < cureent) {
        break;
      }
      this.luckyNum++;
    }
    return this.luckyNum;
  }

  result() {
    const luckyNum = this.luckyNum, list = this.list;
    if (luckyNum) {
      alert("您抽中的是：" + list[luckyNum].title);
    } else{
      alert("很抱歉，" + list[luckyNum].title);
    }
    this.luckyNum = 0;
  }

  handerData(e) {
    const _target = e.target || e.srcElement;
    const parent = _target.parentNode;
    const input = parent.querySelectorAll("input");

    const titleAry = [...input].filter((el) => el.dataset.name === "title");
    const luckyAry = [...input].filter((el) => el.dataset.name === "lucky");
    titleAry.forEach((el, index) => (this.list[index]["title"] = el.value));
    luckyAry.forEach((el, index) => (this.list[index]["p"] = Number(el.value)));
  }
}
